package com.borealis.common.utils.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nonnull;
import lombok.extern.slf4j.Slf4j;

/**
 * 游戏线程池
 *
 * @author yaoweixin
 * @date 2018/7/4
 */
@Slf4j
public class CommonThreadFactory implements ThreadFactory, Thread.UncaughtExceptionHandler {

  /**
   * Daemon state.
   */
  private boolean daemon;
  /**
   * Thread name.
   */
  private String threadName;
  private final AtomicInteger threadNumber = new AtomicInteger(1);

  /**
   * Default constructor.
   *
   * @param threadName name for thread.
   * @param daemon set/unset daemon thread
   */
  public CommonThreadFactory(String threadName, boolean daemon) {
    this.threadName = threadName;
    this.daemon = daemon;
  }

  /**
   * {@inheritDoc}
   *
   * @see ThreadFactory#newThread(Runnable)
   */
  @Override
  public Thread newThread(@Nonnull Runnable r) {
    Thread t = new Thread(r, this.threadName + "-" + threadNumber.getAndIncrement());
    t.setDaemon(this.daemon);
    t.setUncaughtExceptionHandler(this);
    return t;
  }

  /**
   * {@inheritDoc}
   *
   * @see Thread.UncaughtExceptionHandler#uncaughtException(Thread, Throwable)
   */
  @Override
  public void uncaughtException(Thread thread, Throwable throwable) {
    log.error("Uncaught Exception in thread " + thread.getName(), throwable);
  }
}
